import React, { useContext, useEffect, useRef, useState } from 'react';
import { Button, Form, InputNumber, Popconfirm, Table } from 'antd';
import { ITableProps, EditableRowProps, EditableCellProps } from './types';
import type { FormInstance } from 'antd/es/form';
import { isArray } from 'lodash';
import { nmAppErrorLog } from '@app-nextmesh/common/utils';

const EditableContext = React.createContext<FormInstance<any> | null>(null);

// 编辑表格行
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const EditableRow: React.FC<EditableRowProps> = ({ index, ...props }) => {
  const [form] = Form.useForm();
  return (
    <Form
      form={form}
      component={false}>
      <EditableContext.Provider value={form}>
        <tr {...props} />
      </EditableContext.Provider>
    </Form>
  );
};
// 编辑表格单元
const EditableCell: React.FC<EditableCellProps> = ({
  title,
  editable,
  children,
  dataIndex,
  record,
  handleSave,
  ...restProps
}) => {
  const [editing, setEditing] = useState(false);
  const inputRef = useRef<HTMLInputElement>(null);
  const form = useContext(EditableContext)!;

  useEffect(() => {
    if (editing) {
      inputRef.current!.focus();
    }
  }, [editing]);

  const toggleEdit = () => {
    setEditing(!editing);
    form.setFieldsValue({ [dataIndex]: record[dataIndex] });
  };

  const save = async () => {
    try {
      const values = await form.validateFields();

      toggleEdit();
      handleSave({ ...record, ...values });
    } catch (errInfo) {
      nmAppErrorLog('Save failed:', errInfo);
    }
  };

  let childNode = children;

  if (editable) {
    childNode = editing ? (
      <Form.Item
        style={{ margin: 0 }}
        name={dataIndex}
        rules={[
          {
            required: true,
            message: `${title} is required.`,
          },
        ]}>
        <InputNumber
          style={{ width: '80px' }}
          ref={inputRef}
          onPressEnter={save}
          onBlur={save}
        />
      </Form.Item>
    ) : (
      <div
        className='editable-cell-value-wrap'
        style={{ paddingRight: 24 }}
        onClick={toggleEdit}>
        {children}
      </div>
    );
  }

  return <td {...restProps}>{childNode}</td>;
};

type EditableTableProps = Parameters<typeof Table>[0];
type ColumnTypes = Exclude<EditableTableProps['columns'], undefined>;
export default function DynamicTable(props: ITableProps) {
  const [dataSource, setDataSource] = useState<any[]>();
  const [count, setCount] = useState(1);
  const [allTitle, setAllTitle] = useState([]);

  useEffect(() => {
    const values = props.value as any[];
    const allKeys = props.columns.map(({ dataIndex }) => dataIndex);
    setAllTitle(allKeys);
    const tableData = [];
    if (isArray(values)) {
      if (values.length !== 0) {
        const tableLength = values[0][allKeys[0]].length;
        for (let i = 0; i < tableLength; i++) {
          const data = { key: i };
          allKeys.forEach((key, j) => {
            data[key] = values[j][key][i];
          });
          tableData.push(data);
        }
      }
    }
    setDataSource(tableData);
    const maxValue = tableData.length + 1;
    setCount(maxValue);
  }, [props.value]);

  const handleDelete = (key: React.Key) => {
    const newData = dataSource.filter((item) => item.key !== key);
    handleSaveChange(newData);
    setDataSource(newData);
  };
  const defaultColumns: any[] =
    props.columns?.map(
      (item: any) =>
        ({
          title: item.title,
          dataIndex: item.dataIndex,
          width: item.width ? item.width : '100px',
          editable: true,
          fixed: item.fixed,
        }) as any,
    ) || [];
  defaultColumns.push({
    title: 'operation',
    dataIndex: 'operation',
    fixed: 'right', // 固定在右侧
    width: 80,
    align: 'center',
    render: (_, record: { key: React.Key }) =>
      dataSource.length >= 1 ? (
        <Popconfirm
          title='Sure to delete?'
          onConfirm={() => handleDelete(record.key)}>
          <a>Delete</a>
        </Popconfirm>
      ) : null,
  });

  defaultColumns.unshift({
    title: 'No.',
    dataIndex: 'index',
    width: 40,
    key: 'index',
    align: 'center',
    fixed: 'left',
    render: (text, record, index) => index + 1, // 从 1 开始
  });
  const handleAdd = () => {
    const newData = {
      key: count,
    };
    handleSaveChange([...dataSource, newData]);
    setDataSource([...dataSource, newData]);
    setCount(count + 1);
  };

  const handleSave = (row: any) => {
    const newData = [...dataSource];
    const index = newData.findIndex((item) => row.key === item.key);
    const item = newData[index];
    newData.splice(index, 1, {
      ...item,
      ...row,
    });
    handleSaveChange(newData);
    setDataSource(newData);
  };

  const components = {
    body: {
      row: EditableRow,
      cell: EditableCell,
    },
  };

  const columns = defaultColumns.map((col) => {
    if (!col.editable) {
      return col;
    }
    return {
      ...col,
      align: 'center',
      onCell: (record: any) => ({
        record,
        ...col,
        editable: col.editable,
        handleSave,
      }),
    };
  });

  const handleSaveChange = (data: any[]) => {
    const all = [];
    allTitle.forEach((key) => {
      all.push({
        [key]: data.map((item) => item[key]),
      });
    });
    props.onChange?.(all);
  };
  return (
    <div style={{ width: '380px' }}>
      <Button
        onClick={handleAdd}
        type='primary'
        style={{ marginBottom: 16, marginTop: 40 }}>
        Add a row
      </Button>
      <Table
        size='small'
        scroll={{ x: 380 }}
        style={{ width: '100%' }}
        components={components}
        rowClassName={() => 'editable-row'}
        bordered
        // pagination={false}
        dataSource={dataSource}
        columns={columns as ColumnTypes}
      />
    </div>
  );
}
